#coding=utf-8
from pyramid.config import Configurator
from pyramid.authentication import SessionAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from models.user import User
from models.group import Group
from pyramid.security import Allow,Everyone,unauthenticated_userid
from pyramid_beaker import session_factory_from_settings
from pyramid.renderers import JSONP

def get_user(request):
    userid=unauthenticated_userid(request)
    if userid is not None:
        return request.dbsession.query(User).filter_by(id=userid).first()


def groupfinder(userid,request):
    user=request.dbsession.query(User).filter_by(id=userid).first()

    if user:
        return ['g:'+str(user.group_id)]
    return None

class RootFactory(object):
    def __init__(self,request):
        groups=request.dbsession.query(Group).all()
        self.__acl__=[]
        self.__acl__.append((Allow,Everyone,'view'))
        for group in groups:
            for permission in group.permissions:
                self.__acl__.append((Allow,'g:'+str(group.id),permission.name))


def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """

    authn_policy= SessionAuthenticationPolicy(prefix='auth.',callback=groupfinder,debug=True)

    authz_policy=ACLAuthorizationPolicy()
    session_factory=session_factory_from_settings(settings)
    config = Configurator(settings=settings,root_factory='myproject.RootFactory')
    config.set_session_factory(session_factory)
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.set_request_property(get_user,'user',reify=True)
    config.include('pyramid_jinja2')
    config.include('.models')
    config.include('.routes')
    config.scan()
    config.add_renderer('jsonp',JSONP(param_name='callback'))
    return config.make_wsgi_app()

